<template>
  <div class="app-container">
    <div class="header">
      <el-form :inline="true" :model="queryParams" ref="ruleFormRef">
        <el-form-item label="登录地址" prop="ipaddr">
          <el-input
            v-model="queryParams.ipaddr"
            placeholder="请输入登录地址"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="用户名称" prop="userName">
          <el-input
            v-model="queryParams.userName"
            placeholder="请输入用户名称"
            clearable
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="登录状态"
            clearable
            style="width: 240px"
          >
            <el-option
              v-for="dict in dict.type.sys_common_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="登录时间">
          <el-date-picker
            v-model="dateRange"
            style="width: 240px"
            type="daterange"
            value-format="YYYY-MM-DD HH:mm:ss"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="defaultTime"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="footer">
      <div class="util">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['monitor:logininfor:remove']"
          >删除
        </el-button>
        <el-button
          type="danger"
          plain
          icon="Delete"
          @click="handleClean"
          v-hasPermi="['monitor:logininfor:remove']"
          >清空
        </el-button>
        <el-button
          type="primary"
          plain
          icon="Unlock"
          :disabled="single"
          @click="handleUnlock"
          v-hasPermi="['monitor:logininfor:unlock']"
          >解锁
        </el-button>

        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['monitor:logininfor:export']"
          >导出
        </el-button>
      </div>
      <div class="table-inner">
        <el-table
          ref="tableDataRef"
          v-loading="loading"
          :data="tableData"
          :default-sort="defaultSort"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
          @sort-change="handleSortChange"
        >
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="访问编号" align="center" prop="infoId" />
          <el-table-column
            label="用户名称"
            align="center"
            prop="userName"
            :show-overflow-tooltip="true"
            sortable="custom"
            :sort-orders="['descending', 'ascending']"
          />
          <el-table-column
            label="登录地址"
            align="center"
            prop="ipaddr"
            width="130"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="登录地点"
            align="center"
            prop="loginLocation"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="浏览器"
            align="center"
            prop="browser"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="操作系统" align="center" prop="os" />
          <el-table-column label="登录状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="dict.type.sys_common_status" :value="scope.row.status" />
            </template>
          </el-table-column>
          <el-table-column
            label="操作信息"
            align="center"
            prop="msg"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="登录日期"
            align="center"
            prop="loginTime"
            sortable="custom"
            :sort-orders="['descending', 'ascending']"
            width="180"
          >
            <!--            <template #default="scope">
                          <span>{{ (scope.row.loginTime) }}</span>
                        </template>-->
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination">
        <!--分页器            -->
        <el-pagination
          v-show="total > 0"
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[5, 10, 15, 20, 25, 30]"
          :background="true"
          layout="prev, pager, next, jumper, ->,  sizes, total"
          :total="total"
          @current-change="getList"
          @size-change="getList"
        />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
  import { FormInstance } from 'element-plus'
  import DictTag from '@/components/DictTags/index.vue'
  import {
    reqCleanLogininfor,
    reqDelLogininfor,
    reqLogininforListPage,
    reqUnlockLogininfor,
  } from '@/api/monitor/logininfor'
  import { reqBaseData, reqTableData } from '@/api/type'

  const { proxy }: any = getCurrentInstance()
  const ruleFormRef = ref<FormInstance>()
  // 查询参数
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    ipaddr: undefined,
    userName: undefined,
    orderByColumn: undefined,
    isAsc: undefined,
    status: undefined,
    beginTime: '',
    endTime: '',
  })
  // 时间日期
  const dateRange = ref([])
  const total = ref(0)
  const tableData = ref()
  const tableDataRef = ref()
  const single = ref(true)
  const infoIds = ref([])
  const multiple = ref(true)
  const loading = ref(true)
  const selectName = ref('')
  const defaultSort = ref({
    prop: 'loginTime',
    order: 'descending',
  })
  const defaultTime = ref<[Date, Date]>([
    new Date(2000, 1, 1, 0, 0, 0),
    new Date(2000, 2, 1, 23, 59, 59),
  ])
  // 查询
  const handleQuery = async () => {
    queryParams.pageNum = 1
    await getList()
  }

  const getList = async () => {
    loading.value = true
    queryParams.beginTime = dateRange.value[0]
    queryParams.endTime = dateRange.value[1]
    await reqLogininforListPage(queryParams)
      .then((req: reqTableData) => {
        if (req.code === 200) {
          total.value = req.total
          tableData.value = req.rows
        }
      })
      .catch((e) => {
        console.log(e.message)
      })
    setTimeout(() => {
      loading.value = false
      queryParams.beginTime = ''
      queryParams.endTime = ''
    }, 500)
  }

  // 重置查询参数
  const resetQuery = (ElRef) => {
    ElRef.resetFields()
    Object.keys(queryParams).forEach((key) => {
      if (key === 'pageNum') {
        queryParams[key] = 1
      } else if (key === 'pageSize') {
        queryParams[key] = 10
      } else if (key === 'isAsc' || key === 'orderByColumn') {
      } else {
        queryParams[key] = ''
      }
    })
    tableDataRef.value.sort(defaultSort.value.prop, defaultSort.value.order)
    dateRange.value = []
    // 再次查询
    handleQuery()
  }

  /*多选框*/
  const handleSelectionChange = (selection: any) => {
    infoIds.value = selection.map((item: any) => item.infoId)
    single.value = selection.length != 1
    multiple.value = !selection.length
    selectName.value = selection.map((item) => item.userName)
  }

  /** 排序触发事件 */
  const handleSortChange = (column, prop, order) => {
    queryParams.orderByColumn = column.prop
    queryParams.isAsc = column.order
    getList()
  }

  // 删除
  const handleDelete = async () => {
    proxy.$modal
      .confirm('是否确认删除访问编号为"' + infoIds.value + '"的数据项？')
      .then(function () {
        return reqDelLogininfor(infoIds.value)
      })
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('删除成功')
      })
      .catch(() => {})
    /*  await reqDelLogininfor(infoIds.value).then((req: reqBaseData) => {
    if (req.code === 200) {
      proxy.$modal.msgSuccess("删除成功!");
    } else {
      proxy.$modal.msgSuccess("删除失败" + req.message);
    }
  }).catch((e) => {
    console.log("登录日志---删除" + e.message);
  });
  await getList();*/
  }

  // 清空
  const handleClean = async () => {
    proxy.$modal
      .confirm('是否确认清空所有登录日志数据项？')
      .then(function () {
        return reqCleanLogininfor()
      })
      .then(() => {
        getList()
        proxy.$modal.msgSuccess('清空成功')
      })
      .catch(() => {})
    /* await reqCleanLogininfor().then((req: reqBaseData) => {
    if (req.code === 200) {
      proxy.$modal.msgSuccess("清空成功!");
    } else {
      proxy.$modal.msgSuccess("清空失败" + req.message);
    }
  }).catch((e) => {
    console.log("登录日志---清空" + e.message);
  })*/
  }

  const handleExport = () => {
    // 调用接口
    proxy.$download(
      'monitor/logininfor/export',
      { ...queryParams },
      `loginInfo_${new Date().getTime()}.xlsx`,
    )
  }

  // 清除锁定状态
  const handleUnlock = async () => {
    const username = selectName.value
    proxy.$modal
      .confirm('是否确认解锁用户"' + username + '"数据项?')
      .then(function () {
        return reqUnlockLogininfor(username)
      })
      .then(() => {
        proxy.$modal.msgSuccess('用户' + username + '解锁成功')
      })
      .catch(() => {})
    /* await reqUnlockLogininfor().then((req: reqBaseData) => {
    if (req.code === 200) {
      proxy.$modal.msgSuccess("解锁成功!");
    } else {
      proxy.$modal.msgSuccess("删除失败" + req.message);
    }
  }).catch((e) => {
    console.log("登录日志---解锁" + e.message);
  })*/
  }

  onMounted(() => {
    handleQuery()
  })
</script>
<script lang="ts">
  export default {
    dicts: ['sys_oper_type', 'sys_common_status'],
  }
</script>

<style scoped lang="scss">
  @import './index';
</style>
